from django.shortcuts import render, HttpResponse, redirect, reverse
from app01 import models
from django.db.models import Q, F

from 分页器.pagination import Pagination
from app01.forms import Payment_operation, Enroll_operation, Consult_operation, Customer_operation, Register,Classlist_operation,Course_operation,Student_operation
import hashlib
from django.db import transaction


def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        md5 = hashlib.md5()
        md5.update(password.encode('utf-8'))
        password = md5.hexdigest()
        if models.UserProfile.objects.filter(username=username, password=password, is_active=True):
            request.session['login'] = models.UserProfile.objects.filter(username=username)[0].name
            request.session.set_expiry(0)
            return redirect('/customer/')
        else:
            return render(request, 'login.html', {'error': '账号或密码错误'})
    return render(request, 'login.html')


from django import forms


def register(request):
    form_obj = Register()
    if request.method == 'POST':
        form_obj = Register(request.POST)
        if form_obj.is_valid():
            form_obj.save()
            return redirect('/login/')
    return render(request, 'register.html', {'form_obj': form_obj})


from django.views import View


class Customer(View):
    def get(self, request, *args, **kwargs):
        if request.path_info == reverse('customer'):
            all_customer = models.Customer.objects.filter(consultant__isnull=True)
        else:
            all_customer = models.Customer.objects.filter(consultant=request.user_obj)

        q = self.query(['name', 'phone', 'qq'])
        all_customer = all_customer.filter(q)
        page_obj = Pagination(request.GET.get('page', '1'), len(all_customer), request.GET.copy(), 2, 11)
        return render(request, 'customer.html',
                      {
                          'all_customer': all_customer[page_obj.start:page_obj.end],
                          'page_html': page_obj.page_html,
                          'url': reverse('customer')
                      })

    def post(self, request, *args, **kwargs):
        action = request.POST.get('action')
        print(action)
        func = getattr(self, action)
        if not func:
            return HttpResponse('没有此方法')
        ret = func()
        return self.get(request, *args, **kwargs)

    def query(self, field_names):
        query = self.request.GET.get('sou', '')
        q = Q()
        q.connector = 'OR'
        if not query:
            return q
        for field in field_names:
            q.children.append(Q(('{}__contains'.format(field), query)))
        return q

    def multi_apply(self):
        '''
        公户转私户
        :return:
        '''
        pk_list = self.request.POST.getlist('customer_pk')
        from django.conf import settings
        if self.request.user_obj.customer.all().count() + len(pk_list) > settings.MAX_CUSTOMER_NUM:
            return HttpResponse('做人不要太贪心')

        try:

            with transaction.atomic():
                ret = models.Customer.objects.filter(pk__in=pk_list, consultant=None).select_for_update()  # 行级锁
                if len(pk_list) == ret.count():
                    ret.update(consultant=self.request.user_obj)
                else:
                    return HttpResponse('你太慢了，被别人抢走了，请刷新页面!')

        except Enrollment:
            pass

    def multi_pub(self):
        '''
        私户转公户
        :return:
        '''
        pk_list = self.request.POST.getlist('customer_pk')

        models.Customer.objects.filter(pk__in=pk_list).update(consultant=None)


def customerFrom(request, pk=None):
    '''
    客户表增加或编辑客户
    :param request:
    :param pk:
    :return:
    '''
    obj = models.Customer.objects.filter(pk=pk).first()
    form_obj = Customer_operation(instance=obj)
    if request.method == 'POST':
        form_obj = Customer_operation(request.POST, instance=obj)
        if form_obj.is_valid():
            form_obj.save()
            path = request.GET.get('path')
            print(path)
            return redirect(path)
    title = '编辑客户' if pk else '添加客户'
    return render(request, 'all_add.html', {'form_obj': form_obj, 'titlr': title})


class ConsultRecord(View):
    def get(self, request, customer_id=None):
        if customer_id:
            consul_all = models.ConsultRecord.objects.filter(customer_id=customer_id, consultant=self.request.user_obj,
                                                             delete_status=False)
        else:
            consul_all = models.ConsultRecord.objects.filter(consultant=self.request.user_obj, delete_status=False)

        # q=self.query(['customer'])
        # consul_all=consul_all.filter(q)
        page = Pagination(request.GET.get('page'), consul_all.count(), request.GET.copy(), 2, 11)
        return render(request, 'consultrecord.html',
                      {'consul_all': consul_all.order_by('-date')[page.start:page.end], 'page_html': page.page_html})

    # def query(self,field_names):
    #     query = self.request.GET.get('sou','')
    #     q=Q()
    #     q.connector='OR'
    #     if  not query:
    #         return q
    #     for i in field_names:
    #         q.children.append(Q(('{}__contains'.format(i),query)))
    #     return q


def consultFrom(request, pk=None):
    '''
    跟进记录表增加或编辑
    :param request:
    :param pk:
    :return:
    '''
    obj = models.ConsultRecord.objects.filter(pk=pk).first()
    form_obj = Consult_operation(request, instance=obj)
    if request.method == 'POST':
        form_obj = Consult_operation(request, data=request.POST, instance=obj)
        if form_obj.is_valid():
            form_obj.save()
            path = request.GET.get('path')
            print(path)
            return redirect(path)

    title = '编辑跟进记录' if pk else '添加跟进记录'
    return render(request, 'all_add.html', {'form_obj': form_obj, 'title': title})


class Enrollment(View):
    def get(self, request, customer_id=None):
        if customer_id:
            form_obj = models.Enrollment.objects.filter(customer_id=customer_id)
        else:
            form_obj = models.Enrollment.objects.all()
        page = Pagination(request.GET.get('page'), form_obj.count(), request.GET.copy(), 2, 11)
        return render(request, 'enrollment.html',
                      {'enroll_all': form_obj[page.start:page.end], 'page_html': page.page_html})


def enrollFrom(request, customer_id=None, pk=None):
    '''
    报名记录表增加或编辑
    :param request:
    :param pk:
    :return:
    '''
    obj = models.Enrollment(customer_id=customer_id) if customer_id else models.Enrollment.objects.filter(pk=pk).first()
    form_obj = Enroll_operation(instance=obj)
    if request.method == 'POST':
        form_obj = Enroll_operation(data=request.POST, instance=obj)
        if form_obj.is_valid():
            form_obj.save()
            path = request.GET.get('path')
            print(path)
            return redirect(path)

    title = '编辑报名记录' if pk else '添加报名记录'
    return render(request, 'all_add.html', {'form_obj': form_obj, 'title': title})


class Paymentrecord(View):
    def get(self, request):
        payment_all = models.PaymentRecord.objects.all()
        page = Pagination(request.GET.get('page'), payment_all.count(), request.GET.copy(), 2, 11)
        return render(request, 'payment.html',
                      {'payment_all': payment_all[page.start:page.end], 'page_html': page.page_html})


def paymentFrom(request, pk=None):
    obj = models.PaymentRecord.objects.filter(pk=pk).first()
    form_obj = Payment_operation(instance=obj)
    if request.method == 'POST':
        form_obj = Payment_operation(request.POST, instance=obj)
        if form_obj.is_valid():
            form_obj.save()
            path = request.GET.get('path')
            return redirect(path)
    title = '编辑缴费记录' if pk else '添加缴费记录'
    return render(request, 'all_add.html', {'form_obj': form_obj, 'title': title})


class Classlist(View):
    def get(self, request):
        classlist_all = models.ClassList.objects.all()
        page = Pagination(request.GET.get('page'), classlist_all.count(), request.GET.copy(), 2, 11)
        return render(request, 'classlist.html',
                      {'classlist_all': classlist_all[page.start:page.end], 'page_html': page.page_html})

def classForm(request,pk=None):
    obj = models.ClassList.objects.filter(pk=pk).first()
    form_obj = Classlist_operation(instance=obj)
    if request.method == 'POST':
        form_obj = Classlist_operation(request.POST, instance=obj)
        if form_obj.is_valid():
            form_obj.save()
            path = request.GET.get('path')
            return redirect(path)
    title = '编辑班级信息' if pk else '添加班级信息'
    return render(request, 'all_add.html', {'form_obj': form_obj, 'title': title})

class Courserecord(View):
    def get(self,request,class_id=None):
        course_all = models.CourseRecord.objects.filter(re_class_id=class_id)
        page = Pagination(request.GET.get('page'), course_all.count(), request.GET.copy(), 2, 11)
        return render(request, 'courserecord.html',
                      {'course_all': course_all[page.start:page.end], 'page_html': page.page_html,'class_id':class_id})

    def post(self, request, *args, **kwargs):
        action = request.POST.get('action')
        print(action)
        func = getattr(self, action)
        if not func:
            return HttpResponse('没有此方法')
        ret = func()
        return self.get(request, *args, **kwargs)
    def multi_init(self):
        '''
        批量初始化学习记录
        :return:
        '''
        pklist = self.request.POST.getlist('customer_pk')
        for id in pklist:
            students = models.CourseRecord.objects.filter(pk=id).first().re_class.customer_set.filter(status='studying')
            list = []
            for student in students:
                if not models.StudyRecord.objects.filter(course_record_id=id,student=student).exists():
                    list.append(models.StudyRecord(course_record_id=id,student=student))
            models.StudyRecord.objects.bulk_create(list)



def courseForm(request,class_id=None,pk=None):
    obj = models.CourseRecord(re_class_id=class_id,recorder=request.user_obj) if class_id else models.CourseRecord.objects.filter(pk=pk).first()
    form_obj = Course_operation(instance=obj)
    if request.method == 'POST':
        form_obj = Course_operation(request.POST, instance=obj)
        if form_obj.is_valid():
            form_obj.save()
            path = request.GET.get('path')
            return redirect(path)
    title = '编辑课程信息' if pk else '添加课程信息'
    return render(request, 'all_add.html', {'form_obj': form_obj, 'title': title,'class_id':class_id})
from django.forms import modelformset_factory
def studentForm(request,courserecord_id=None):
    ModelFormSet = modelformset_factory(models.StudyRecord,Student_operation,extra=0)
    queryset = models.StudyRecord.objects.filter(course_record_id=courserecord_id)
    form_set = ModelFormSet(queryset=queryset)
    if request.method=='POST':
        form_set = ModelFormSet(data=request.POST)
        if form_set.is_valid():
            form_set.save()
    return render(request,'studyrecord.html',{'form_set':form_set})

def page(request):
    list = [{'user': '时光{}'.format(i), 'password': 'shiguang{}'.format(i)} for i in range(1, 1000)]
    num = 20  # 一页展示20行数据
    nums = 11  # 分页显示个数
    try:
        page = int(request.GET.get('page', '1'))  # 获取传过来的页数，获取不到默认为1
    except Exception:
        page = 1
    if page <= 0:
        page = 1
    amount, mod = divmod(len(list), num)  # 计算分页数量，有余数加1
    if mod:
        amount += 1
    page_start = (page - 1) * num
    page_end = page * num
    amount_start = page - (nums - 1) // 2  # 页数显示的起始数
    amount_end = page + (nums - 1) // 2  # 页数显示的末尾数
    # 进行判断前面是否有足够的数据
    if amount_start <= 0:
        amount_start = 1
        amount_end = nums
    # 进行判断后面是否有足够的数据
    elif amount_end >= amount:
        amount_start = amount - nums
        amount_end = amount

    return render(request, 'page.html',
                  {'list': list[page_start:page_end], 'amount': [i for i in range(amount_start, amount_end + 1)],
                   'page': page, 'pagep': page - 1, 'pagen': page + 1, 'count': amount})
